﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using FineUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;

namespace IHISCETeim.Web.AgentSys.SysMgr
{
    public partial class AgentUserList : AgentPageBase
    {

        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get { return "AgentUserList"; }
        }

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton(Permission.修改, btnChangeEnableUsers);
            CheckPowerWithButton(Permission.删除, btnDeleteSelected);
            CheckPowerWithButton(Permission.新增, btnNew);



            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid1);

            ResolveEnableStatusButtonForGrid(btnEnableUsers, Grid1, true);
            ResolveEnableStatusButtonForGrid(btnDisableUsers, Grid1, false);

            btnNew.OnClientClick = Window1.GetShowReference("AgentUserAdd.aspx", "新增经销商用户");


            this.ddlRoleId.DataSource = ORoleController.GetAll().Select("IsAgent=1").ToList();
            this.ddlRoleId.DataBind();

            // 每页记录数
            Grid1.PageSize = PageSize;
            ddlGridPageSize.SelectedValue = PageSize.ToString();

            BindGrid();
        }

        private void ResolveEnableStatusButtonForGrid(MenuButton btn, Grid grid, bool enabled)
        {
            string enabledStr = "启用";
            if (!enabled)
            {
                enabledStr = "禁用";
            }
            btn.OnClientClick = grid.GetNoSelectionAlertInParentReference("请至少应该选择一项记录！");
            btn.ConfirmText = String.Format("确定要{1}选中的<span class=\"highlight\"><script>{0}</script></span>项记录吗？", grid.GetSelectedCountReference(), enabledStr);
            btn.ConfirmTarget = FineUI.Target.Self;
        }

        private void BindGrid()
        {
            //IQueryable<User> q = DB.Users; //.Include(u => u.Dept);

            //// 在用户名称中搜索
            //string searchText = ttbSearchMessage.Text.Trim();
            //if (!String.IsNullOrEmpty(searchText))
            //{
            //    q = q.Where(u => u.Name.Contains(searchText) || u.ChineseName.Contains(searchText) || u.EnglishName.Contains(searchText));
            //}

            //if (GetIdentityName() != "admin")
            //{
            //    q = q.Where(u => u.Name != "admin");
            //}

            //// 过滤启用状态
            //if (rblEnableStatus.SelectedValue != "all")
            //{
            //    q = q.Where(u => u.Enabled == (rblEnableStatus.SelectedValue == "enabled" ? true : false));
            //}

            //// 在查询添加之后，排序和分页之前获取总记录数
            //Grid1.RecordCount = q.Count();

            //// 排列和数据库分页
            //q = SortAndPage<User>(q, Grid1);

            string RealName = ttbSearchMessage.Text.Trim(); 
            Grid1.DataSource = OUserController.GetPagination(RealName, this.ddlRoleId.SelectedValue, 2, Grid1.PageIndex+1, Grid1.PageSize, Grid1.SortField + " " + Grid1.SortDirection, ref TotalCount);
            Grid1.RecordCount = TotalCount;
            Grid1.DataBind();
        }

        #endregion

        #region Events

        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithWindowField(Permission.修改, Grid1, "editField");
            CheckPowerWithLinkButtonField(Permission.删除, Grid1, "deleteField");
            CheckPowerWithWindowField(Permission.修改, Grid1, "changePasswordField");

        }

        protected void Grid1_PreRowDataBound(object sender, FineUI.GridPreRowEventArgs e)
        {           
           
        }
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            DataRowView dr = e.DataItem as DataRowView;
            try
            {
                int SrvActUserId = Convert.ToInt32(dr["SrvActUserId"].ToString());
                System.Web.UI.WebControls.Label xx = Grid1.Rows[e.RowIndex].FindControl("SrvActUserName") as System.Web.UI.WebControls.Label;
                OUserInfo objUser = OUserController.GetById(SrvActUserId);
                xx.Text = objUser == null ? "" : objUser.RealName;
            }
            catch { 
            
            }
        }
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!HasPower(Permission.删除))
            {
                CheckPowerFailWithAlert();
                return;
            }
            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid1);
            // 执行数据库操作 
            foreach (int id in ids)
            {
                OUserController.Delete(id);
               
            }  
            // 重新绑定表格
            BindGrid();
        }

        protected void btnEnableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(true);
        }

        protected void btnDisableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(false);
        }


        private void SetSelectedUsersEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!HasPower(Permission.修改))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid1);
            // 执行数据库操作
            foreach (int id in ids)
            {
                OUserController.ChangeState(id,enabled?1:0);
               
            }
            Grid1.PageIndex = 0;
            // 重新绑定表格
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            int userID = GetSelectedDataKeyID(Grid1);           

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!HasPower(Permission.删除))
                {
                    CheckPowerFailWithAlert();
                    return;
                }
               //执行删除代码
                if (OUserController.Delete(userID))
                {
                    BindGrid();
                }
                else
                {
                    Alert.Show("删除失败");
                    return;
                }
            }
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            Grid1.PageIndex = 0;
            BindGrid();
        }

        protected void rblEnableStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageIndex = 0;
            BindGrid();
        }


        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);
            Grid1.PageIndex = 0;
            BindGrid();
        }



        #endregion

        protected void ddlRoleId_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageIndex = 0;
            BindGrid();
        }
    }
}